package cn.shiro.shiroservice.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * &#064;Time 2024 二月 星期四 17:27
 *
 * @author ShangGuan
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyErrorController implements ErrorController {
    private static final Logger log = LoggerFactory.getLogger(MyErrorController.class);


    /**
     * Method to execute when the error path is requested.
     * This will return a 404, 405, 415 or 500 error depending on the status to the client.
     *
     * @param request The request object.
     */
    @RequestMapping
    public void error(HttpServletRequest request) {
        log.error("发生异常兜底");
       throw new RuntimeException("服务器异常");
    }

    /**
     * Retrieve the http status from the request.
     * @param request The request object.
     * @return The HTTP status code to return.
     */
    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        //if http status is null then return internal server error
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
